/**
 * Created by bob on 14-2-17.
 */
var fs = require('fs');
var httpsync = require('httpsync');
var mkdirOrig = fs.mkdir,
    mkdirSyncOrig = fs.mkdirSync,
    osSep = process.platform === 'win32' ? '\\' : '/';

function mkdirSync_p(path, mode, position) {
    var parts = require('path').normalize(path).split(osSep);

    mode = mode || process.umask();
    position = position || 0;

    if (position >= parts.length) {
        return true;
    }

    var directory = parts.slice(0, position + 1).join(osSep) || osSep;
    try {
        fs.statSync(directory);
        mkdirSync_p(path, mode, position + 1);
    } catch (e) {
        try {
            mkdirSyncOrig(directory, mode);
            mkdirSync_p(path, mode, position + 1);
        } catch (e) {
            if (e.code != 'EEXIST') {
                throw e;
            }
            mkdirSync_p(path, mode, position + 1);
        }
    }
}

module.exports = {
    base64EncodeFromUrl: function (url) {
        url.substr(0,5).toLowerCase()=='https' && (url = 'http'+url.substr(5));
        var req = httpsync.get({ url: url});
        var resp = req.end();
//        console.log(resp);
        var bitmap = resp.data;
        var buffer = new Buffer(bitmap);
        return buffer.toString('base64');
    },
    mkdirSync_p: mkdirSync_p
}